<template>
  <div>
     
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10"
        >添加体重数据</Button
      >
      <Button
        type="primary"
        :loading="refreshLoading"
        @click="refreshEvent"
        shape="circle"
        icon="md-refresh"
        class="fr"
      ></Button>
      <Select v-model="searchTypeValue" class="searchInputClass">
        <Option
          v-for="item in searchType"
          :value="item.value"
          :key="item.value"
          >{{ item.label }}</Option
        >
      </Select>
      <Input
        v-model="searchKeyWord"
        placeholder="请输入搜索关键字"
        suffix="ios-search"
        class="searchKeyWordInputClass"
      />
    </Card>
    <Row  style="margin-bottom:20px">
      <Col :xs="24" :sm="24" :md="24" :lg="24">
        <Card>
          <Tables
            ref="tables"
            editable
            v-model="searchData"
            :columns="columns"
            :loading="loading"
            :border="true"
            size="large"
          />
        </Card>
        <Page
          :total="num"
          @on-change="changePage"
          show-sizer
          show-elevator
          show-total
          :page-size="pageSize"
          :page-size-opts="$store.state.pageSizeArray"
          @on-page-size-change="changePageSize"
          style="margin-top: 12px; float: right"
        />
      </Col>
    </Row> 
    <Card>
      <WeightDataView></WeightDataView>
    </Card>
    <Modal
      title="添加数据"
      v-model="addModal"
      :styles="{ top: '50px' }"
      @on-ok="addDataEvent"
    >
      <Form :model="addData" :label-width="80">
        <FormItem label="日期：" prop="date">
          <Input
            v-model="addData.date"
            type="date"
            placeholder="请选择日期."
          ></Input>
        </FormItem>
        <FormItem label="姓名：" prop="name">
          <Input
            v-model="addData.name"
            maxlength="10"
            type="text"
            placeholder="请输入姓名，字数不超过10字。"
          ></Input>
        </FormItem>
        <FormItem label="体重：" prop="weight">
          <Input-number
            :max="999.9"
            :min="0"
            v-model="addData.weight"
            autoFocus
            :step="1"
          ></Input-number
          >（斤）
        </FormItem>
      </Form>
    </Modal>

    <Modal
      title="修改体重数据"
      v-model="editTodoListModal"
      :styles="{ top: '50px' }"
      @on-ok="editDataEvent"
    >
      <Form :model="editData" :label-width="80">
        <FormItem label="日期：" prop="date">
          <Input
            v-model="editData.date"
            type="date"
            placeholder="请选择日期."
          ></Input>
        </FormItem>
        <FormItem label="姓名：">
          <Input
            v-model="editData.name"
            maxlength="10"
            type="text"
            placeholder="请输入姓名，字数不超过10字。"
          ></Input>
        </FormItem>
        <FormItem label="体重：" prop="weight">
          <Input-number
            :max="999"
            :min="1"
            v-model="editData.weight"
            autoFocus
            :step="1"
          ></Input-number
          >（斤）
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import {
  getWeightData,
  addWeightData,
  deleteWeightData,
  editWeightData,
} from "@/api/content/health/weight.js";
import WeightDataView from "./WeightDataView.vue";
export default {
  name: "tables_page",
  components: {
    Tables,
    WeightDataView
  },
  data() {
    return {
      refreshLoading: false,
      addData: { name: "杨鑫", weight: null },
      addModal: false,
      editData: {},
      editTodoListModal: false,
      num: 0,
      columns: [
        { title: "日期", key: "date", sortable: true, width: 120 },
        { title: "姓名", key: "name" },
        { title: "体重（斤）", key: "weight",width:150},
        {
          title: "操作",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.editData.weight = parseFloat(this.editData.weight);
                      this.showEditModal();
                    },
                  },
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?",
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除");
                    },
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning",
                      },
                      style: {
                        marginRight: "5px",
                      },
                    },
                    "删除"
                  ),
                ]
              ),
            ]);
          },
        },
      ],
      tableData: [],
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      searchType: [
        {
          label: "日期",
          value: "date",
        },
        {
          label: "姓名",
          value: "name",
        },
        {
          label: "体重",
          value: "weight",
        },
      ],
      searchTypeValue: "",
      searchKeyWord: "",
    };
  },
  methods: {
    //添加体重数据
    addDataEvent() {
      this.addData.weight = parseFloat(this.addData.weight);
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        addWeightData(this.addData).then((res) => {
          if (res.data.code == 0) {
            this.getData(this.pageCurrent, this.pageSize);
            this.$Message.success("您成功添加了一条体重数据.");
          } else if (res.data.code == 1010) {
            this.$Message.error("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您添加体重数据失败了，错误原因：" + res.data.msg);
          }
        });
      }
    },
    editDataEvent() {
      if (!this.requireFormData(this.editData)) {
        return false;
      } else {
        editWeightData(this.editData)
          .then((res) => {
            if (res.data.code == 0) {
              this.columns[this.editData._index] = this.editData;
              this.$Message.success("您成功修改了一条体重数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改体重数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch((err) => {
            this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    requireFormData(data) {
      if (!data.name || data.name.length > 10) {
        this.$Message.warning(
          "您输入的姓名格式错误，字数在1-10位之间，请重新输入."
        );
        return false;
      } else if (!data.date || data.date.length !== 10) {
        this.$Message.warning("您选择的日期格式错误，请重新选择.");
        return false;
      } else if (data.weight < 1 || data.weight.length > 999) {
        this.$Message.warning(
          "您输入的体重格式错误，数值应在在0-1000位之间，请重新输入."
        );
        return false;
      } else {
        return true;
      }
    },
    //删除体重数据
    deleteDataEvent(row) {
      deleteWeightData(row.id)
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一个体重数据.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error("您删除体重数据失败了，错误原因：" + res.data.msg);
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },
    //打开添加页面
    showAddModal() {
      this.addModal = true;
    },

    //打开修改页面
    showEditModal() {
      this.editTodoListModal = true;
    },
    //获取表格体重数据
    getData(page, pageNum) {
      this.loading = true;
      getWeightData(page, pageNum)
        .then((res) => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            this.loading = false;
            this.refreshLoading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //第几页体重数据
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示体重数据
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    },
    formatDate() {
      let nowDate = new Date();
      let y = nowDate.getFullYear();
      let m = nowDate.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = nowDate.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + m + "-" + d;
    },
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.pageCurrent, this.pageSize);
    this.addData.date = this.formatDate();
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter((item) => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    },
  },
};
</script>
<style scope>

</style>